import Koa from 'koa';

export class Api {
  private ctx: Koa.Context;

  constructor(ctx: Koa.Context) {
    this.ctx = ctx;
  }

  private res(code = 0, data: IAnyObject | null, msg = ''): void {
    this.ctx.status = 200;
    this.ctx.set('Content-Type', 'application/json');
    this.ctx.body = {
      code,
      msg,
      data,
    };
  }

  // 成功
  success(data: IAnyObject, msg = ''): void {
    return this.res(0, data, msg);
  }

  // 失败
  fail(code = -1, msg = ''): void {
    return this.res(code, null, msg);
  }
}

export default function apiMiddleare(): Koa.Middleware<
  Koa.DefaultState,
  Koa.DefaultContext
> {
  return (ctx: Context, next: Next): Promise<void> => {
    ctx.api = new Api(ctx);
    return next();
  };
}
